<template>
  <div ref="target" class="rbt-city">
    <div class="select" :class="{ active }" @click="toggleDialog">
      <span v-if="!fullLocation" class="placeholder">{{ placeholder }}</span>
      <span class="placeholder">{{ fullLocation }}</span>
      <span class="value"></span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div v-if="active" class="option">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span
          v-for="item in currList"
          :key="item.code"
          class="ellipsis"
          @click="changeItem(item)"
          >{{ item.name }}</span
        >
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import { onClickOutside } from '@vueuse/core'
import { ResultType } from '@/types/goods'
interface CityDataType {
  code: string
  level: number
  name: string
  areaList: CityDataType[]
}

const emits = defineEmits<{
  (e: 'change', value: ResultType): void
}>()

defineProps({
  fullLocation: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: ''
  }
})

// 在内存中缓存城市数据
const getCityData = () => {
  return new Promise<CityDataType[]>(resolve => {
    let cityData = JSON.parse(window.sessionStorage.getItem('cityData'))
    if (cityData) {
      resolve(cityData)
    } else {
      const url =
        'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
      axios.get(url).then(res => {
        window.sessionStorage.setItem('cityData', JSON.stringify(res.data))
        resolve(res.data)
      })
    }
  })
}

// 控制展开和收起
const active = ref(false)
const cityData = ref<CityDataType[]>([])
const loading = ref(false)
const openDialog = () => {
  active.value = true
  loading.value = true
  // 获取数据
  getCityData().then(data => {
    cityData.value = data
    loading.value = false
  })
  // 清空选择结果
  for (const key in changeResult) {
    changeResult[key] = ''
  }
}

const currList = computed(() => {
  // 省份
  let currList = cityData.value
  // 城市
  if (changeResult.provinceCode) {
    currList = currList.find(p => p.code === changeResult.provinceCode).areaList
  }

  // 地区
  if (changeResult.cityCode) {
    currList = currList.find(c => c.code === changeResult.cityCode).areaList
  }

  return currList
})

const closeDialog = () => {
  active.value = false
}

// 切换展开收起
const toggleDialog = () => {
  if (active.value) closeDialog()
  else openDialog()
}

// 点击其他位置隐藏
const target = ref(null)
onClickOutside(target, () => {
  closeDialog()
})

const changeResult = reactive<ResultType>({
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  countryCode: '',
  countryName: '',
  fullLocation: ''
})

const changeItem = (item: CityDataType) => {
  // 省份
  if (item.level === 0) {
    changeResult.provinceCode = item.code
    changeResult.provinceName = item.name
  }

  // 市
  if (item.level === 1) {
    changeResult.cityCode = item.code
    changeResult.cityName = item.name
  }

  // 地区
  if (item.level === 2) {
    changeResult.countryCode = item.code
    changeResult.countryName = item.name
    changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countryName}`
    closeDialog()
    emits('change', changeResult)
  }
}
</script>

<style scoped lang="scss">
.rbt-city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    .loading {
      height: 290px;
      width: 100%;
      background: url(../assets/images/loading.gif) no-repeat center;
    }
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
